package engineer.clientapp.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import engineer.clientapp.beans.User;
import engineer.clientapp.tools.Tool;

public class RemindPasswordAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String target = null;
		User loginForm = (User) form;
		String email = loginForm.getEmail();
		ActionErrors actionErrors = new ActionErrors();
		System.err.println("Haslo: " + email);
		if (!(email == null || email.equals(""))) {
			if (Tool.checkEmailFormat(email)) {
				if (Tool.remindPassword(email)) {
					target = "success";
					actionErrors.add("info", new ActionMessage(
							"error.sendpassword"));
				} else {
					target = "failure";
					actionErrors.add("info", new ActionMessage("error.nouser"));
				}
			} else {
				target = "failure";
				actionErrors
						.add("info", new ActionMessage("error.emailFormat"));
			}
		} else {
			target = "failure";
			actionErrors.add("info", new ActionMessage("error.emptyFields"));
		}
		if (actionErrors.size() != 0) {
			extracted(request, actionErrors);
			return new ActionForward(mapping.getInput());
		}

		return mapping.findForward(target);
	}

	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}

}
